//
//  HHYCustomTopView.m
//  大股票
//
//  Created by apple on 2019/8/14.
//  Copyright © 2019 apple. All rights reserved.
//

#import "HHYCustomTopView.h"

#import "HHYHeader.h"

@interface HHYCustomTopView ()

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *selectedBtnArr;
@property (weak, nonatomic) IBOutlet UIView *lineView;

@property (nonatomic, strong) UIView *contentView;

@end

@implementation HHYCustomTopView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        [self addSubview:self.contentView];
        
        [self updateUI];
    }
    
    return self;
}

- (void)updateUI
{
    //默认选中第一个
    [self selectedAction:self.selectedBtnArr.firstObject];
    //设置选中及未选中状态
    for (UIButton *btn in self.selectedBtnArr) {
        [btn setTitleColor:rgba(255, 163, 133, 1) forState:UIControlStateNormal];
        [btn setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
    }
}

- (IBAction)selectedAction:(UIButton *)sender {
    
    if ([self.selectedBtnArr containsObject:sender]) {
        [self selectedActionWithBtn:sender];
        return;
    }
    
}

#pragma mark - 选中Action
- (void)selectedActionWithBtn:(UIButton *)btn
{
    //重置
    for (UIButton *btn in self.selectedBtnArr) {
        btn.selected = NO;
    }
    //设置为选中状态
    btn.selected = YES;
    NSInteger index = [self.selectedBtnArr indexOfObject:btn];
    //滑动下划线
    [UIView animateWithDuration:0.25 animations:^{
        CGPoint center = [self convertPoint:btn.center fromView:btn.superview];
        self.lineView.xl_centerX = center.x;
    }];
    
    if (self.handler) {
        self.handler(index);
    }
}


#pragma mark - getter
- (UIView *)contentView {
    if (!_contentView) {
        UINib *nib = [UINib nibWithNibName:@"hhy_CustomTopView" bundle:nil];
        NSArray *objs = [nib instantiateWithOwner:self options:nil];
        _contentView = objs[0];
        _contentView.frame = self.bounds;
    }
    return _contentView;
}

@end
